<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use mysql_xdevapi\Exception;

class NeedPassCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        try {
            $request->validate([
                'password' => 'required'
            ]);
            $user = User::find(Auth()->user()->id);
            if (!$user || !Hash::check($request->password, $user->password)) {
                return response()->json([
                    'code' => 422,
                    'message' => '登录失败，请检查密码',
                ]);
            }
        } catch (\Exception $e) {
            return response()->json([
                'code' => 422,
                'message' => '登录失败，请检查密码',
            ]);
        }
        return $next($request);
    }
}
